const router = require('koa-router')()
const db = require('../utils/database')

// 前缀
router.prefix('/classify')

router.get('/', async ctx => {
    const r = await db.doSQL('select * from classify where id > 30')
    console.log(r)
    ctx.body = 'classify' + JSON.stringify(r)
})

// 分类列表、分页、排序、查询
router.get('/classify-list', async ctx => {
    const { page = 0, pageSize = 20, sortBy, order = 'desc', query } = ctx.query
    let sql = `select * from classify`
    if (query) {
        sql += ` where name like '%${query}%'`
    }
    if (sortBy) {
        sql += ` order by ${sortBy} ${order}`
    }
    sql += ` limit ${page * pageSize},${pageSize}`
    const r = await db.doSQL(sql)
    const sqlTotal = 'select count(*) as total from classify'
    const rTotal = await db.doSQL(sqlTotal)
    const total = rTotal[0].total
    ctx.body = db.doResponse({ message: '分类列表', data: r, total: total })
})

// 删除
router.get('/delete-classify', async ctx => {
    const { id } = ctx.query
    const sql = 'delete from classify where id=?'
    const r = await db.doSQL(sql, [id])
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '删除类别成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5001, message: '删除用户失败', data: r })
    }
})

// 修改用户
router.post('/update-classify', async ctx => {
    const { name, id } = ctx.request.body
    const sql = 'update classify set name=? where id=?'
    const params = [name, id]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '修改类别成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5001, message: '修改类别失败', data: r })
    }
})

// 新增用户 
router.post('/save-classify', async ctx => {
    const { name } = ctx.request.body
    const sql = 'insert into classify(name) values (?)'
    const params = [name]
    const r = await db.doSQL(sql, params)
    console.log(r)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '新增类别成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5001, message: '新增类别失败', data: r })
    }

})

module.exports = router